<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="作者" prop="username">
        <el-input
          v-model="queryParams.username"
          placeholder="请输入作者"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="课程名称" prop="courseName">
        <el-input
          v-model="queryParams.courseName"
          placeholder="请输入课程名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="课程搜索关键字" prop="coursePrimary">
        <el-input
          v-model="queryParams.coursePrimary"
          placeholder="请输入课程搜索关键字"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['siyun-course:course:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['siyun-course:course:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['siyun-course:course:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="4">
        <el-tree
          :data="treeData"
          :props="defaultProps"
          @node-click="handleNodeClick"
        ></el-tree>
      </el-col>
      <el-col :span="20">
        <el-table v-loading="loading" :data="courseList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="课程主键" align="center" prop="id" />
          <el-table-column label="作者" align="center" prop="username" />
          <el-table-column label="课程名称" align="center" prop="courseName" />
          <el-table-column label="课程简介" align="center" prop="courseIntro">
            <template slot-scope="scope">
              <div v-html="scope.row.courseIntro"></div>
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center" prop="remarks" />
          <el-table-column label="上架状态" align="center" prop="courseStatus">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.courseStatus"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-value="2"
                :inactive-value="3"
                @change="handleChangeStatus(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="审核状态" align="center" prop="courseCstatus" :formatter="formatcourseCstatus"/>
          <el-table-column label="缩略图" align="center" prop="thum" width="100">
            <template slot-scope="scope">
              <image-preview :src="scope.row.thum" :width="50" :height="50"/>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-view"
                @click="handleView(scope.row)"
                v-hasPermi="['siyun:course:list']"
              >查看</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['siyun:course:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['siyun:course:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改课程对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="作者" prop="username">
              <el-select v-model="form.username" placeholder="请选择">
                <el-option
                  v-for="item in restaurants"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="课程名称" prop="courseName" style="width: 288px">
              <el-input v-model="form.courseName" placeholder="请输入课程名称" :readonly="isViewing"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-descriptions-item label="课程简介" style="width: 288px">
              <div v-html="form.courseIntro"></div>
            </el-descriptions-item>
          </el-col>
          <el-col :span="12">
            <el-descriptions-item label="备注"   style="width: 288px">
              <div v-html="form.remarks"></div>
            </el-descriptions-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="课程价格" prop="courseNprice" style="width: 288px">
              <el-input v-model="form.courseNprice" placeholder="请输入课程现价" :readonly="isViewing"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="课程分类" prop="classify" style="width: 288px">
              <el-select  placeholder="请选择" v-model="form.classify">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
          </el-col>
          <el-col :span="12">
            <el-form-item label="缩略图" prop="thum">
              <image-upload v-model="form.thum" :disabled="isViewing"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="课程视频" prop="imgUrls">
              <!--              <el-input v-model="form.imgUrls" placeholder="请输入课程视频" :readonly="isViewing"/>-->
              <el-button @click="addvidos">点击跳转视频添加</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="!isViewing" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看课程对话框 -->
    <el-dialog :title="title" :visible.sync="viewOpen" width="1000px" append-to-body custom-class="view-dialog">
      <el-descriptions class="margin-top" :column="3" :size="size" border>
        <!-- Top Section -->
        <el-descriptions-item label="作者">{{ form.username }}</el-descriptions-item>
        <el-descriptions-item label="课程名称">{{ form.courseName }}</el-descriptions-item>
        <el-descriptions-item label="课程视频"><el-button @click="imgUrlss">点击观看</el-button></el-descriptions-item>
        <el-descriptions-item label="缩略图">
          <image-preview :src="form.thum" :width="200" :height="200"/>
        </el-descriptions-item>
        <el-descriptions-item label="课程简介">{{ form.courseIntro }}</el-descriptions-item>
        <el-descriptions-item label="备注">{{ form.remarks }}</el-descriptions-item>
        <el-descriptions-item label="课程原价">{{ form.coursePrice }}</el-descriptions-item>
        <el-descriptions-item label="课程现价">{{ form.courseNprice }}</el-descriptions-item>
        <el-descriptions-item label="课程搜索关键字">
          <el-tag v-for="tag in form.coursePrimary" :key="tag" style="margin-right: 5px;">{{ tag }}</el-tag>
        </el-descriptions-item>
      </el-descriptions>
      <br />
      <el-descriptions class="margin-top" :column="2" :size="size" border>
        <!-- Middle Section -->
        <el-descriptions-item label="点赞数量">{{ form.likeNum }}</el-descriptions-item>
        <el-descriptions-item label="分享数量">{{ form.shareNum }}</el-descriptions-item>
        <el-descriptions-item label="收藏数量">{{ form.collectNum }}</el-descriptions-item>
        <el-descriptions-item label="预览数量">{{ form.lookNum }}</el-descriptions-item>
        <el-descriptions-item label="销售数量">{{ form.saleNum }}</el-descriptions-item>
      </el-descriptions>
      <br />
      <!-- Bottom Section -->
      <el-descriptions class="margin-top" :column="2" :size="size" border>
        <el-descriptions-item label="创建人">{{ form.createBy }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ form.createTime }}</el-descriptions-item>
        <el-descriptions-item label="修改人">{{ form.updateBy }}</el-descriptions-item>
        <el-descriptions-item label="修改时间">{{ form.updateTime }}</el-descriptions-item>
      </el-descriptions>

      <!-- 他人评论区块 -->
      <div>
        <h3>评论</h3>
        <el-table
          v-loading="loading"
          :data="comments"
          row-key="id"
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          style="width: 100%"
          height="400"
          border
        >
          <el-table-column label="回复人" width="150" align="center" prop="username" fixed />
          <el-table-column label="头像" width="100" align="center" prop="avatar">
            <template slot-scope="scope">
              <image-preview :src="scope.row.avatar" :width="50" :height="50"/>
            </template>
          </el-table-column>
          <el-table-column label="回复内容" align="center" prop="content" >
            <template slot-scope="scope">
              <div v-html="scope.row.content"></div>
            </template>
          </el-table-column>
          <el-table-column label="回复时间戳" align="center" prop="replytime" width="150">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.replytime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
             <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-chat-dot-square"
                  @click="toggleReply(scope.row)"
                >回复</el-button>
             </template>
          </el-table-column>
        </el-table>
      </div>
      <!--回复评论-->
      <div v-for="row in courseList" :key="row.id">
        <div v-if="replyStates[row.id]">
          <el-input
            type="textarea"
            :rows="4"
            placeholder="请输入评论"
            v-model="comment"
          />
          <el-button type="primary" @click="addComment(row.id)">提交评论</el-button>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="viewClose">关 闭</el-button>
      </div>
    </el-dialog>



  </div>
</template>

<script>
import { listCourse, getCourse, delCourse, addCourse, updateCourse, courseCategoryTree} from "@/api/siyun/course";
import {listCategory} from "@/api/siyun/category"
import {listUsers} from "@/api/siyun/appusers/appusers"
import { listComment2, addComment } from "@/api/comment/comment.js";
export default {
  name: "Course",
  data() {
    return {
      //评论
      comment: '',
      comments: [],
      commentParams: {
        commentId: null,
        type: 2
      },
      // 添加回复状态
      replyStates: {},
      // 课程分类数组
      options:[],
      // 树形数据
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      tableData: [],
      classify: '',
      size: 'medium',
      viewOpen: false, // 控制查看对话框的显示与隐藏
      value1:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 课程表格数据
      courseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否为查看模式
      isViewing: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        username: null,
        courseName: null,
        coursePrimary: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        username: [
          { required: true, message: "作者不能为空", trigger: "blur" }
        ],
        courseName: [
          { required: true, message: "课程名称不能为空", trigger: "blur" }
        ],
        coursePrice: [
          { required: true, message: "课程原价不能为空", trigger: "blur" }
        ],
        courseNprice: [
          { required: true, message: "课程现价不能为空", trigger: "blur" }
        ]
      },
      // 自动完成建议列表
      restaurants: []
    };
  },
  created() {
    this.getList();
    this.getusrelis();
    this.getCourseCategorylist()
    this.getCourseCategoryTree();
    var open = this.$store.state.shipin.open;
    var videomessage = this.$store.state.shipin.videomessage;
    var videolist = this.$store.state.shipin.videolist;
    if (videomessage != null && videomessage != undefined && videomessage != ''){
      var parse = JSON.parse(videomessage);
      this.form = parse;
    }
    if (open == true) {
      this.open = true;
    }

  },
  mounted() {
    // this.restaurants
  },
  methods: {
    getComment() {
      this.comments = []; // 清空 comments 数组
      listComment2(this.commentParams).then(response => {
        this.comments = this.handleTree(response.data, "id", "pid");
      }).catch(error => {
        console.error("获取评论信息失败:", error);
        this.$modal.msgError("获取评论信息失败，请稍后再试");
      });
    },
    handleTree(data, id, pid) {
      const map = {};
      const result = [];
      data.forEach(item => {
        map[item[id]] = { ...item, children: [] };
      });
      data.forEach(item => {
        if (item[pid] !== null && map[item[pid]]) {
          map[item[pid]].children.push(map[item[id]]);
        } else {
          result.push(map[item[id]]);
        }
      });
      return result;
    },
    // 评论
    addComment(pid) {
      if (this.comment.trim() === '') {
        this.$message.warning('未书写评论内容');
        return;
      }
      const newComment = {
        userId: this.userProfile.userId, // 假设 userProfile 包含当前用户的 userId
        content: this.comment,
        pid: pid
      };
      addComment(newComment).then(response => {
        this.$message.success('评论成功');
        this.comment = ''; // 清空评论框
        this.getComment(); // 重新获取评论数据
      }).catch(error => {
        console.error("提交评论失败:", error);
        this.$message.error("提交评论失败，请稍后再试");
      });
    },

    // 切换回复状态
    toggleReply(row) {
      this.$set(this.replyStates, row.id, !this.replyStates[row.id]);
    },
    //获取课程分类列表
    getCourseCategorylist(){
      listCategory().then(response => {
        var data = response.data;
        data.forEach(item =>{
          this.options.push({value:item.categoryId,label:item.categoryName})
        })
      })
    },
    //获取用户信息
    getusrelis(){
      listUsers().then(response => {


        var rows = response.rows;
        rows.forEach(item =>{
          this.restaurants.push({value:item.id,label:item.username})
        })
      })
    },
    //视频传值给vuex
    imgUrlss(){
      this.$store.commit('shipin/SET_VIDEOCOURSEID',this.form.id);
      //跳转视频列表页面
      this.$router.push({ path: '/course/coures/video' });
    },
    //添加视频对话框
    addvidos(){
      this.$router.push({path: '/course/coures/videolist'});
      this.$store.commit('shipin/SET_ADDORUPDATE',1)
      this.$store.commit('shipin/SET_VIDEOMESSAGE',JSON.stringify(this.form))
    },
    //树形数据条件查询
    handleNodeClick(data){
      this.queryParams.classify = data.id;
      this.handleQuery();
    },
    //树形数据显示
    getCourseCategoryTree() {
      courseCategoryTree().then(response => {
        this.treeData = response.data; // 假设response.data是树形数据
      }).catch(error => {
        console.error('获取课程分类树失败', error);
      });
    },
    //关闭查看窗口
    viewClose() {
      this.viewOpen = false;
      this.reset();
    },
    formatcourseCstatus(row) {
      const statusMap = {
        2: '已审核',
        3: '未审核',
        4: '审核中',
        5: '审核失败',
        6: '其他',
      };
      return statusMap[row.courseCstatus] || '未知';
    },
    handleChangeStatus(row) {
      const newStatus = row.courseStatus === 2 ? 2 : 3;
      updateCourse({ id: row.id, courseStatus: newStatus })
        .then(response => {
          this.$message.success("状态更新成功")
          this.getList(); // 刷新列表以反映最新状态
        })
        .catch(error => {
          this.$message.error("状态更新失败")
          row.courseStatus = row.courseStatus === 2 ? 3 : 2; // 回滚状态
        });
    },
    /** 查询课程列表 */
    getList() {
      this.loading = true;
      listCourse(this.queryParams).then(response => {

        this.courseList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {};
      this.isViewing = false;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.title = "添加课程";
      this.open = true;
      this.$store.commit('shipin/SET_VIDEOCOURSEID',0)
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const courseId = row.id || this.ids[0];
      this.$store.commit("shipin/SET_VIDEOCOURSEID",courseId)
      this.$store.commit('shipin/SET_ADDORUPDATE',2)
      getCourse(courseId).then(response => {
        this.form = response.data;
        this.title = "修改课程";
        this.open = true;
      });
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.reset();
      const courseId = row.id;
      this.commentParams.commentId = courseId; // 设置 commentId
      this.getComment(); // 获取评论数据
      getCourse(courseId).then(response => {
        this.form = response.data;
        this.title = "查看课程";
        this.viewOpen = true; // 打开查看对话框
      });
    },
    /** 提交按钮 */
    submitForm() {
      if (this.$store.state.shipin.videolist != null && this.$store.state.shipin.videolist != undefined && this.$store.state.shipin.videolist != ''){
        var parse = JSON.parse(this.$store.state.shipin.videolist);
      }
      this.form.courseStatus = 2;
      this.form.syCourseVideos = parse;
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCourse(this.form).then(response => {
              this.$store.commit('shipin/SET_OPEN', false)
              this.$store.commit('shipin/SET_DEMO', null)
              this.$store.commit('shipin/SET_VIDEOMESSAGE', '')
              this.$store.commit('shipin/SET_VIDEOLIST', '')
              this.$message.success("修改成功")
              this.open = false;
              this.getList();
            });
          } else {
            addCourse(this.form).then(response => {
              this.$store.commit('shipin/SET_OPEN', false)
              this.$store.commit('shipin/SET_DEMO', null)
              this.$store.commit('shipin/SET_VIDEOMESSAGE', '')
              this.$store.commit('shipin/SET_VIDEOLIST', '')
              this.$message.success("新增成功")
              this.reset();
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const courseIds = row.id || this.ids;
      this.$confirm('是否确认删除课程编号为"' + courseIds + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return delCourse(courseIds);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/course/export', {
        ...this.queryParams
      }, `course_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped>
.view-dialog .el-form-item {
  margin-bottom: 15px;
}

.view-dialog .el-form-item__label {
  font-weight: bold;
}

.view-dialog .el-tag {
  margin-top: 5px;
}

.view-dialog .el-row:not(:last-child) {
  margin-bottom: 20px;
}
</style>
